package pa165.dominatingspecies.frontend.user;

import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import pa165.dominating.species.service.UserService;
import pa165.dominating.species.tos.UserTO;
import pa165.dominatingspecies.frontend.pages.BasePage;

import java.util.List;
import org.springframework.security.access.prepost.PreAuthorize;

import pa165.dominating.species.enums.UserType;
import pa165.dominatingspecies.frontend.element.EnumPropertyModel;

/**
 * @author Tomas Kalla
 */
@PreAuthorize("hasRole('ADMIN')")
public class UserPage extends BasePage {

    @SpringBean(name = "userService")
    private UserService userService;

    public UserPage() {
        initGui();
    }

    private void initGui() {
        addEnvironmentsModule();
        addNewEnvironmentLink();
    }

    private void addEnvironmentsModule() {
        ListView<UserTO> listView = new ListView<UserTO>("listview", createModelForEnvironments()) {
            @Override
            protected void populateItem(ListItem<UserTO> item) {
                final UserTO userTO = item.getModelObject();
                item.add(new Label("id", new PropertyModel(item.getModel(), "id")));
                item.add(new Label("name", new PropertyModel(item.getModel(), "name")));
                item.add(new Label("login", new PropertyModel(item.getModel(), "login")));
                item.add(new Label("userType", new EnumPropertyModel<UserType>(item.getModel(), "type", this)));

                item.add(new EditUserLink("edit", userTO.getId()));
                item.add(new UserDetailLink("details", userTO.getId()));
                item.add(new DeleteUserLink("delete", item.getModelObject()));

            }
        };
        add(listView);
    }

    private LoadableDetachableModel<List<UserTO>> createModelForEnvironments() {
        return new LoadableDetachableModel<List<UserTO>>() {
            @Override
            protected List<UserTO> load() {
                return userService.getAllUsers();
            }
        };
    }

    private void addNewEnvironmentLink() {
        add(new Link("createUserLink") {
            @Override
            public void onClick() {
                setResponsePage(new CreateUserPage());
            }
        });
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }
}
